use std::io::Read;
use std::io::Write;
use std::net::{TcpListener, TcpStream};

fn main() {
  println!("start...");
  run();
  println!("end...");
}

fn run() {
  fn _handle_client(mut stream: TcpStream) {
    let ref mut v = vec![0; 100];
    let _ret = stream.read(v);
    match _ret {
      Ok(count) => {
        println!("count:{}, v:{:?}", count, v);
        let ref vv: Vec<u8> = v
          .iter()
          .filter(|&&_v| {
            if _v != 0 {
              return true;
            } else {
              return false;
            }
          })
          .map(|&_v| {
            return _v;
          })
          .collect();
        let __ret = stream.write(vv);
        match __ret {
          Ok(_count) => {
            println!("_count:{}, vv:{:?}", _count, vv);
          }
          Err(_error) => {
            eprintln!("{}:{}", count, _error);
          }
        }
      }
      Err(error) => {
        eprintln!("{}", error);
      }
    }
  }

  fn _test() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:45566")?;

    // accept connections and process them serially
    for stream in listener.incoming() {
      _handle_client(stream?);
    }
    //  let ret = std::thread::Thread::from(|_|{
    //     _test();
    //  });
    Ok(())
  }
  let ret = _test();
  println!("{:?}", ret);
}

#[test]
fn test() {
  fn _test() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:45566")?;
    let v = String::from("hello world");
    let send_buf = v.as_bytes();
    stream.write(send_buf)?;
    let ref mut r = vec![0;15];
    let r_count = stream.read(r).expect("msg");
    println!("_test: v:{:?}, r:{:?}, r_c:{:?}", v, r, r_count);
    Ok(())
  } // the stream is closed here
  let ret = _test();
  println!("{:?}", ret);
}
